package service

import (
	"context"

	"github.com/bwmarrin/snowflake"
	"github.com/google/uuid"
	"github.com/samber/do/v2"

	"gitee.com/monkeyPP/happy-mall/services/productservice/internal/domain/entity"
	"gitee.com/monkeyPP/happy-mall/services/productservice/internal/interfaces/api/request"
)

type ProductService interface {
	ProcessAddProduct(context.Context, *request.AddProductRequest) (*entity.Product, error)
}

type ProductServiceImpl struct {
	snowflakeNode *snowflake.Node
}

func NewProductService(i do.Injector) (ProductService, error) {
	node, err := snowflake.NewNode(1)
	if err != nil {
		panic(err)
	}
	return &ProductServiceImpl{
		snowflakeNode: node,
	}, nil
}

func (p *ProductServiceImpl) ProcessAddProduct(ctx context.Context, req *request.AddProductRequest) (*entity.Product, error) {
	if req.GoodsSN == "" {
		req.GoodsSN = p.genGoodsSN()
	}

	product := &entity.Product{
		ID:          p.snowflakeNode.Generate().Int64(),
		Name:        req.Name,
		GoodsSN:     req.GoodsSN,
		CategoryID:  req.CategoryID,
		Description: req.Description,
	}

	product.SkuList = make([]*entity.Sku, len(req.Skus), len(req.Skus))

	for idx, item := range req.Skus {
		product.SkuList[idx] = &entity.Sku{
			ID:          p.snowflakeNode.Generate().Int64(),
			ProductID:   product.ID,
			SkuSN:       p.genSkuSN(),
			ShopPrice:   item.ShopPrice,
			MarketPrice: item.MarketPrice,
			Attributes:  item.Attributes,
		}
	}
	return product, nil
}

func (p *ProductServiceImpl) genGoodsSN() string {
	return "SN" + uuid.New().String()
}

func (p *ProductServiceImpl) genSkuSN() string {
	return "SKU" + uuid.New().String()
}
